from exlib.flask_restplus.formats import BaseTable, BaseResponse, ListResponseMixin
from flask_restplus import fields as frp_fields
from exlib.flex import current_api
Model = current_api.model


class QttTable(BaseTable):
    """一个范例"""
    TABLE_FORMAT = {
        'code': frp_fields.Integer(attribute='_code'),
        'message': frp_fields.String,
        'total': frp_fields.Integer,
        'current_page': frp_fields.Integer(attribute='page'),
        'total_page': frp_fields.Integer(attribute='_total_page'),
    }

    @property
    def _code(self):
        if hasattr(self, 'code'):
            return self.code
        return 0

    @property
    def _total_page(self):
        if hasattr(self, 'total_page'):
            return self.total_page
        return int((self.total - 1) / self.page_size) + 1 if self.page_size!= -1 else 1


class QttSucResponse(BaseResponse):
    FORMAT = {
        'code': frp_fields.Integer(attribute='_code'),
        'message': frp_fields.String
    }

    @property
    def _code(self):
        if hasattr(self, 'code'):
            return self.code
        return 0


class SkvSucResponse(BaseResponse):
    FORMAT = {
        'status': frp_fields.Integer(attribute='_status'),
        'message': frp_fields.String
    }

    @property
    def _status(self):
        if hasattr(self, 'status'):
            return self.status
        return 200


class SkvTable(BaseTable):
    TABLE_FORMAT = {
        'status': frp_fields.Integer(attribute='_status'),
        'message': frp_fields.String,
        'total': frp_fields.Integer,
        # 'current_page': frp_fields.Integer(attribute='page'),
        'total_page': frp_fields.Integer(attribute='_total_page'),
    }

    @property
    def _status(self):
        if hasattr(self, 'status'):
            return self.status
        return 200

    @property
    def _total_page(self):
        if hasattr(self, 'total_page'):
            return self.total_page
        return int((self.total - 1) / self.page_size) + 1 if self.page_size!= -1 else 1


class ListResponse(SkvSucResponse, ListResponseMixin):
    pass


error_fields = Model('error_400', {
    'status': frp_fields.Integer,
    'message': frp_fields.String
})
